#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
享元模式 (Flyweight Pattern) - Python实现详解

享元模式是一种结构设计模式，它通过共享技术来有效支持大量细粒度对象的复用。
享元模式可以避免大量非常相似类的开销，在程序设计中有时需要生成大量细粒度的类实例来表示数据。

与Java对比：
1. Python的弱引用(weakref)模块提供了更灵活的对象管理
2. Python的__new__方法可以控制对象创建过程
3. Python的字典和集合操作更加简洁
4. Python支持更灵活的元类编程

作者: Assistant
日期: 2024
"""

import weakref
import time
import sys
from abc import ABC, abstractmethod
from typing import Dict, Any, Optional, List, Set, Tuple
from dataclasses import dataclass
from enum import Enum
import threading
from collections import defaultdict
import json


# ============================================================================
# 1. 传统享元模式实现
# ============================================================================

class Flyweight(ABC):
    """
    享元接口
    定义享元对象的接口，通过这个接口享元可以接受并作用于外部状态
    """
    
    @abstractmethod
    def operation(self, extrinsic_state: Any) -> Any:
        """执行操作，接受外部状态作为参数"""
        pass


class ConcreteFlyweight(Flyweight):
    """
    具体享元类
    实现享元接口，并为内部状态增加存储空间
    """
    
    def __init__(self, intrinsic_state: Any):
        """初始化内部状态"""
        self._intrinsic_state = intrinsic_state
    
    def operation(self, extrinsic_state: Any) -> Any:
        """执行操作，结合内部状态和外部状态"""
        return f"内部状态: {self._intrinsic_state}, 外部状态: {extrinsic_state}"
    
    @property
    def intrinsic_state(self) -> Any:
        """获取内部状态"""
        return self._intrinsic_state
    
    def __str__(self) -> str:
        return f"ConcreteFlyweight(内部状态={self._intrinsic_state})"
    
    def __repr__(self) -> str:
        return self.__str__()


class FlyweightFactory:
    """
    享元工厂
    创建并管理享元对象，确保合理地共享享元
    """
    
    def __init__(self):
        self._flyweights: Dict[Any, Flyweight] = {}
        self._creation_count = 0
    
    def get_flyweight(self, intrinsic_state: Any) -> Flyweight:
        """获取享元对象，如果不存在则创建"""
        if intrinsic_state not in self._flyweights:
            self._flyweights[intrinsic_state] = ConcreteFlyweight(intrinsic_state)
            self._creation_count += 1
            print(f"创建新的享元对象: {intrinsic_state}")
        else:
            print(f"复用现有享元对象: {intrinsic_state}")
        
        return self._flyweights[intrinsic_state]
    
    def get_flyweight_count(self) -> int:
        """获取享元对象数量"""
        return len(self._flyweights)
    
    def get_creation_count(self) -> int:
        """获取创建次数"""
        return self._creation_count
    
    def list_flyweights(self) -> List[Flyweight]:
        """列出所有享元对象"""
        return list(self._flyweights.values())
    
    def clear(self) -> None:
        """清除所有享元对象"""
        self._flyweights.clear()
        self._creation_count = 0


# ============================================================================
# 2. 字符享元模式实现
# ============================================================================

class CharacterType(Enum):
    """字符类型"""
    LETTER = "LETTER"
    DIGIT = "DIGIT"
    PUNCTUATION = "PUNCTUATION"
    WHITESPACE = "WHITESPACE"


@dataclass(frozen=True)
class CharacterStyle:
    """字符样式（内部状态）"""
    font_family: str
    font_size: int
    color: str
    bold: bool = False
    italic: bool = False
    
    def __str__(self) -> str:
        style_attrs = []
        if self.bold:
            style_attrs.append("粗体")
        if self.italic:
            style_attrs.append("斜体")
        
        style_str = ", ".join(style_attrs) if style_attrs else "普通"
        return f"{self.font_family} {self.font_size}px {self.color} ({style_str})"


@dataclass
class CharacterContext:
    """字符上下文（外部状态）"""
    x: int
    y: int
    character: str
    
    def __str__(self) -> str:
        return f"'{self.character}' at ({self.x}, {self.y})"


class Character(Flyweight):
    """
    字符享元类
    """
    
    def __init__(self, style: CharacterStyle):
        self._style = style
    
    def operation(self, context: CharacterContext) -> str:
        """渲染字符"""
        return f"渲染字符 '{context.character}' 在位置 ({context.x}, {context.y}) 使用样式 {self._style}"
    
    def render(self, context: CharacterContext) -> str:
        """渲染字符的别名方法"""
        return self.operation(context)
    
    @property
    def style(self) -> CharacterStyle:
        """获取字符样式"""
        return self._style
    
    def __str__(self) -> str:
        return f"Character(样式={self._style})"


class CharacterFactory:
    """
    字符工厂
    管理字符享元对象
    """
    
    def __init__(self):
        self._characters: Dict[CharacterStyle, Character] = {}
        self._lock = threading.Lock()  # 线程安全
    
    def get_character(self, style: CharacterStyle) -> Character:
        """获取字符享元对象"""
        with self._lock:
            if style not in self._characters:
                self._characters[style] = Character(style)
                print(f"创建新的字符享元: {style}")
            
            return self._characters[style]
    
    def get_character_count(self) -> int:
        """获取字符享元数量"""
        return len(self._characters)
    
    def get_memory_usage(self) -> int:
        """获取内存使用量（字节）"""
        return sum(sys.getsizeof(char) for char in self._characters.values())
    
    def list_styles(self) -> List[CharacterStyle]:
        """列出所有样式"""
        return list(self._characters.keys())


class Document:
    """
    文档类
    使用字符享元来表示文档内容
    """
    
    def __init__(self, character_factory: CharacterFactory):
        self._character_factory = character_factory
        self._characters: List[Tuple[Character, CharacterContext]] = []
    
    def add_character(self, char: str, x: int, y: int, style: CharacterStyle) -> None:
        """添加字符"""
        character_flyweight = self._character_factory.get_character(style)
        context = CharacterContext(x, y, char)
        self._characters.append((character_flyweight, context))
    
    def add_text(self, text: str, start_x: int, start_y: int, style: CharacterStyle) -> None:
        """添加文本"""
        x, y = start_x, start_y
        for char in text:
            if char == '\n':
                x = start_x
                y += style.font_size + 2
            else:
                self.add_character(char, x, y, style)
                x += style.font_size // 2
    
    def render(self) -> List[str]:
        """渲染文档"""
        return [char.render(context) for char, context in self._characters]
    
    def get_character_count(self) -> int:
        """获取字符总数"""
        return len(self._characters)
    
    def get_flyweight_count(self) -> int:
        """获取享元对象数量"""
        return self._character_factory.get_character_count()
    
    def get_memory_savings(self) -> Dict[str, Any]:
        """计算内存节省"""
        total_characters = len(self._characters)
        flyweight_count = self._character_factory.get_character_count()
        
        # 假设每个字符对象占用100字节
        without_flyweight = total_characters * 100
        with_flyweight = flyweight_count * 100 + total_characters * 20  # 上下文占用20字节
        
        savings = without_flyweight - with_flyweight
        savings_percentage = (savings / without_flyweight) * 100 if without_flyweight > 0 else 0
        
        return {
            "总字符数": total_characters,
            "享元对象数": flyweight_count,
            "不使用享元内存": f"{without_flyweight} 字节",
            "使用享元内存": f"{with_flyweight} 字节",
            "节省内存": f"{savings} 字节",
            "节省百分比": f"{savings_percentage:.1f}%"
        }


# ============================================================================
# 3. 图形享元模式实现
# ============================================================================

class ShapeType(Enum):
    """图形类型"""
    CIRCLE = "CIRCLE"
    RECTANGLE = "RECTANGLE"
    TRIANGLE = "TRIANGLE"


@dataclass(frozen=True)
class ShapeStyle:
    """图形样式（内部状态）"""
    shape_type: ShapeType
    color: str
    border_width: int = 1
    border_color: str = "black"
    
    def __str__(self) -> str:
        return f"{self.shape_type.value}({self.color}, 边框:{self.border_color} {self.border_width}px)"


@dataclass
class ShapeContext:
    """图形上下文（外部状态）"""
    x: int
    y: int
    width: int
    height: int
    
    def __str__(self) -> str:
        return f"位置:({self.x}, {self.y}), 大小:{self.width}x{self.height}"


class Shape(Flyweight):
    """
    图形享元类
    """
    
    def __init__(self, style: ShapeStyle):
        self._style = style
    
    def operation(self, context: ShapeContext) -> str:
        """绘制图形"""
        return self.draw(context)
    
    def draw(self, context: ShapeContext) -> str:
        """绘制图形"""
        shape_info = f"绘制{self._style.shape_type.value}"
        style_info = f"颜色:{self._style.color}, 边框:{self._style.border_color} {self._style.border_width}px"
        position_info = f"位置:({context.x}, {context.y}), 大小:{context.width}x{context.height}"
        
        return f"{shape_info} - {style_info} - {position_info}"
    
    def get_area(self, context: ShapeContext) -> float:
        """计算面积"""
        if self._style.shape_type == ShapeType.CIRCLE:
            radius = min(context.width, context.height) / 2
            return 3.14159 * radius * radius
        elif self._style.shape_type == ShapeType.RECTANGLE:
            return context.width * context.height
        elif self._style.shape_type == ShapeType.TRIANGLE:
            return (context.width * context.height) / 2
        return 0
    
    @property
    def style(self) -> ShapeStyle:
        """获取图形样式"""
        return self._style
    
    def __str__(self) -> str:
        return f"Shape({self._style})"


class ShapeFactory:
    """
    图形工厂
    管理图形享元对象
    """
    
    def __init__(self):
        self._shapes: Dict[ShapeStyle, Shape] = {}
        self._creation_stats = defaultdict(int)
    
    def get_shape(self, style: ShapeStyle) -> Shape:
        """获取图形享元对象"""
        if style not in self._shapes:
            self._shapes[style] = Shape(style)
            self._creation_stats[style.shape_type] += 1
            print(f"创建新的图形享元: {style}")
        
        return self._shapes[style]
    
    def get_shape_count(self) -> int:
        """获取图形享元数量"""
        return len(self._shapes)
    
    def get_creation_stats(self) -> Dict[ShapeType, int]:
        """获取创建统计"""
        return dict(self._creation_stats)
    
    def list_styles(self) -> List[ShapeStyle]:
        """列出所有样式"""
        return list(self._shapes.keys())


class Canvas:
    """
    画布类
    使用图形享元来绘制图形
    """
    
    def __init__(self, shape_factory: ShapeFactory):
        self._shape_factory = shape_factory
        self._shapes: List[Tuple[Shape, ShapeContext]] = []
    
    def add_shape(self, style: ShapeStyle, x: int, y: int, width: int, height: int) -> None:
        """添加图形"""
        shape_flyweight = self._shape_factory.get_shape(style)
        context = ShapeContext(x, y, width, height)
        self._shapes.append((shape_flyweight, context))
    
    def draw_all(self) -> List[str]:
        """绘制所有图形"""
        return [shape.draw(context) for shape, context in self._shapes]
    
    def calculate_total_area(self) -> float:
        """计算总面积"""
        return sum(shape.get_area(context) for shape, context in self._shapes)
    
    def get_shape_count(self) -> int:
        """获取图形总数"""
        return len(self._shapes)
    
    def get_flyweight_count(self) -> int:
        """获取享元对象数量"""
        return self._shape_factory.get_shape_count()
    
    def get_shapes_by_type(self, shape_type: ShapeType) -> List[Tuple[Shape, ShapeContext]]:
        """按类型获取图形"""
        return [(shape, context) for shape, context in self._shapes 
                if shape.style.shape_type == shape_type]


# ============================================================================
# 4. 线程安全的享元工厂
# ============================================================================

class ThreadSafeFlyweightFactory:
    """
    线程安全的享元工厂
    使用弱引用来管理享元对象
    """
    
    def __init__(self):
        self._flyweights: weakref.WeakValueDictionary = weakref.WeakValueDictionary()
        self._lock = threading.RLock()
        self._creation_count = 0
        self._access_count = 0
    
    def get_flyweight(self, key: Any, factory_func: callable) -> Any:
        """获取享元对象，如果不存在则使用工厂函数创建"""
        with self._lock:
            self._access_count += 1
            
            # 尝试从缓存中获取
            flyweight = self._flyweights.get(key)
            if flyweight is not None:
                return flyweight
            
            # 创建新的享元对象
            flyweight = factory_func(key)
            self._flyweights[key] = flyweight
            self._creation_count += 1
            
            return flyweight
    
    def get_statistics(self) -> Dict[str, Any]:
        """获取统计信息"""
        with self._lock:
            return {
                "当前享元数量": len(self._flyweights),
                "总创建次数": self._creation_count,
                "总访问次数": self._access_count,
                "缓存命中率": f"{((self._access_count - self._creation_count) / self._access_count * 100):.1f}%" if self._access_count > 0 else "0%"
            }
    
    def clear(self) -> None:
        """清除所有享元对象"""
        with self._lock:
            self._flyweights.clear()
            self._creation_count = 0
            self._access_count = 0


# ============================================================================
# 5. 享元模式装饰器实现
# ============================================================================

def flyweight(key_func: callable = None):
    """
    享元模式装饰器
    自动为类添加享元功能
    """
    def decorator(cls):
        # 存储享元对象的字典
        _instances = {}
        _lock = threading.Lock()
        
        # 保存原始的__new__方法
        original_new = cls.__new__
        
        def new_new(cls_ref, *args, **kwargs):
            # 生成键
            if key_func:
                key = key_func(*args, **kwargs)
            else:
                key = (args, tuple(sorted(kwargs.items())))
            
            with _lock:
                if key not in _instances:
                    # 创建新实例
                    if original_new is object.__new__:
                        instance = original_new(cls_ref)
                    else:
                        instance = original_new(cls_ref, *args, **kwargs)
                    _instances[key] = instance
                
                return _instances[key]
        
        # 添加类方法来获取统计信息
        @classmethod
        def get_flyweight_count(cls_ref):
            return len(_instances)
        
        @classmethod
        def clear_flyweights(cls_ref):
            with _lock:
                _instances.clear()
        
        # 替换__new__方法
        cls.__new__ = new_new
        cls.get_flyweight_count = get_flyweight_count
        cls.clear_flyweights = clear_flyweights
        
        return cls
    
    return decorator


@flyweight(lambda color, size: (color, size))
class ColoredCircle:
    """
    使用装饰器实现的彩色圆形享元
    """
    
    def __init__(self, color: str, size: int):
        self.color = color
        self.size = size
        print(f"创建彩色圆形: {color}, 大小: {size}")
    
    def draw(self, x: int, y: int) -> str:
        """绘制圆形"""
        return f"在位置({x}, {y})绘制{self.color}圆形，大小:{self.size}"
    
    def __str__(self) -> str:
        return f"ColoredCircle({self.color}, {self.size})"


# ============================================================================
# 6. 演示函数
# ============================================================================

def demonstrate_basic_flyweight():
    """
    演示基本享元模式
    """
    print("\n=== 基本享元模式演示 ===")
    
    factory = FlyweightFactory()
    
    # 创建和使用享元对象
    print("\n=== 创建享元对象 ===")
    flyweight1 = factory.get_flyweight("类型A")
    flyweight2 = factory.get_flyweight("类型B")
    flyweight3 = factory.get_flyweight("类型A")  # 应该复用现有对象
    flyweight4 = factory.get_flyweight("类型C")
    flyweight5 = factory.get_flyweight("类型B")  # 应该复用现有对象
    
    print(f"\n享元对象数量: {factory.get_flyweight_count()}")
    print(f"创建次数: {factory.get_creation_count()}")
    
    # 验证对象复用
    print("\n=== 验证对象复用 ===")
    print(f"flyweight1 is flyweight3: {flyweight1 is flyweight3}")
    print(f"flyweight2 is flyweight5: {flyweight2 is flyweight5}")
    
    # 使用享元对象
    print("\n=== 使用享元对象 ===")
    external_states = ["外部状态1", "外部状态2", "外部状态3"]
    
    for i, flyweight in enumerate([flyweight1, flyweight2, flyweight3]):
        result = flyweight.operation(external_states[i])
        print(f"享元{i+1}: {result}")


def demonstrate_character_flyweight():
    """
    演示字符享元模式
    """
    print("\n=== 字符享元模式演示 ===")
    
    # 创建字符工厂和文档
    char_factory = CharacterFactory()
    document = Document(char_factory)
    
    # 定义一些样式
    title_style = CharacterStyle("Arial", 24, "blue", bold=True)
    body_style = CharacterStyle("Times", 12, "black")
    code_style = CharacterStyle("Courier", 10, "green")
    
    print("\n=== 添加文档内容 ===")
    
    # 添加标题
    document.add_text("Python享元模式", 10, 10, title_style)
    
    # 添加正文
    document.add_text("享元模式是一种结构设计模式\n它通过共享技术来有效支持大量细粒度对象的复用", 
                     10, 50, body_style)
    
    # 添加代码
    document.add_text("class Flyweight:\n    pass", 10, 100, code_style)
    
    # 显示内存节省统计
    print("\n=== 内存使用统计 ===")
    savings = document.get_memory_savings()
    for key, value in savings.items():
        print(f"{key}: {value}")
    
    # 显示享元对象信息
    print("\n=== 享元对象信息 ===")
    print(f"字符享元数量: {document.get_flyweight_count()}")
    print(f"总字符数: {document.get_character_count()}")
    
    print("\n=== 使用的样式 ===")
    for style in char_factory.list_styles():
        print(f"- {style}")


def demonstrate_shape_flyweight():
    """
    演示图形享元模式
    """
    print("\n=== 图形享元模式演示 ===")
    
    # 创建图形工厂和画布
    shape_factory = ShapeFactory()
    canvas = Canvas(shape_factory)
    
    # 定义一些样式
    red_circle = ShapeStyle(ShapeType.CIRCLE, "red", 2, "black")
    blue_rect = ShapeStyle(ShapeType.RECTANGLE, "blue", 1, "gray")
    green_triangle = ShapeStyle(ShapeType.TRIANGLE, "green", 3, "darkgreen")
    
    print("\n=== 添加图形 ===")
    
    # 添加多个图形，其中一些使用相同的样式
    canvas.add_shape(red_circle, 10, 10, 50, 50)
    canvas.add_shape(blue_rect, 70, 10, 80, 40)
    canvas.add_shape(red_circle, 160, 10, 30, 30)  # 复用红色圆形样式
    canvas.add_shape(green_triangle, 200, 10, 60, 60)
    canvas.add_shape(blue_rect, 10, 80, 100, 50)   # 复用蓝色矩形样式
    canvas.add_shape(red_circle, 120, 80, 40, 40)  # 复用红色圆形样式
    
    print(f"总图形数: {canvas.get_shape_count()}")
    print(f"享元对象数: {canvas.get_flyweight_count()}")
    
    # 显示创建统计
    print("\n=== 创建统计 ===")
    stats = shape_factory.get_creation_stats()
    for shape_type, count in stats.items():
        print(f"{shape_type.value}: {count} 个享元对象")
    
    # 计算总面积
    total_area = canvas.calculate_total_area()
    print(f"\n总面积: {total_area:.2f}")
    
    # 按类型显示图形
    print("\n=== 按类型显示图形 ===")
    for shape_type in ShapeType:
        shapes = canvas.get_shapes_by_type(shape_type)
        print(f"{shape_type.value}: {len(shapes)} 个")


def demonstrate_thread_safe_flyweight():
    """
    演示线程安全的享元工厂
    """
    print("\n=== 线程安全享元工厂演示 ===")
    
    factory = ThreadSafeFlyweightFactory()
    
    def create_string_flyweight(key):
        """创建字符串享元的工厂函数"""
        print(f"创建字符串享元: {key}")
        return f"String-{key}"
    
    def worker(worker_id: int, keys: List[str]):
        """工作线程函数"""
        print(f"工作线程 {worker_id} 开始")
        for key in keys:
            flyweight = factory.get_flyweight(key, create_string_flyweight)
            print(f"工作线程 {worker_id} 获取享元: {key} -> {flyweight}")
            time.sleep(0.01)  # 模拟一些工作
    
    # 创建多个线程
    import threading
    
    threads = []
    keys_per_thread = [
        ["A", "B", "C", "A", "B"],
        ["B", "C", "D", "C", "A"],
        ["C", "D", "E", "D", "B"]
    ]
    
    print("\n=== 启动多线程测试 ===")
    for i, keys in enumerate(keys_per_thread):
        thread = threading.Thread(target=worker, args=(i+1, keys))
        threads.append(thread)
        thread.start()
    
    # 等待所有线程完成
    for thread in threads:
        thread.join()
    
    # 显示统计信息
    print("\n=== 统计信息 ===")
    stats = factory.get_statistics()
    for key, value in stats.items():
        print(f"{key}: {value}")


def demonstrate_flyweight_decorator():
    """
    演示享元装饰器
    """
    print("\n=== 享元装饰器演示 ===")
    
    print("\n=== 创建彩色圆形 ===")
    
    # 创建多个彩色圆形，其中一些参数相同
    circle1 = ColoredCircle("red", 10)
    circle2 = ColoredCircle("blue", 15)
    circle3 = ColoredCircle("red", 10)    # 应该复用circle1
    circle4 = ColoredCircle("green", 20)
    circle5 = ColoredCircle("blue", 15)   # 应该复用circle2
    
    print(f"\n享元对象数量: {ColoredCircle.get_flyweight_count()}")
    
    # 验证对象复用
    print("\n=== 验证对象复用 ===")
    print(f"circle1 is circle3: {circle1 is circle3}")
    print(f"circle2 is circle5: {circle2 is circle5}")
    
    # 使用圆形对象
    print("\n=== 绘制圆形 ===")
    positions = [(10, 10), (50, 20), (90, 30), (130, 40), (170, 50)]
    circles = [circle1, circle2, circle3, circle4, circle5]
    
    for i, (circle, pos) in enumerate(zip(circles, positions)):
        result = circle.draw(pos[0], pos[1])
        print(f"圆形{i+1}: {result}")


def demonstrate_performance_comparison():
    """
    演示性能对比
    """
    print("\n=== 性能对比演示 ===")
    
    # 测试数据
    num_objects = 1000
    num_unique_styles = 10
    
    print(f"\n=== 创建 {num_objects} 个对象，{num_unique_styles} 种样式 ===")
    
    # 不使用享元模式
    print("\n--- 不使用享元模式 ---")
    start_time = time.time()
    
    non_flyweight_objects = []
    for i in range(num_objects):
        style_id = i % num_unique_styles
        # 每次都创建新的样式对象
        style = CharacterStyle(f"Font{style_id}", 12 + style_id, f"color{style_id}")
        char = Character(style)
        non_flyweight_objects.append(char)
    
    non_flyweight_time = time.time() - start_time
    non_flyweight_memory = sum(sys.getsizeof(obj) for obj in non_flyweight_objects)
    
    print(f"创建时间: {non_flyweight_time:.4f}秒")
    print(f"内存使用: {non_flyweight_memory} 字节")
    
    # 使用享元模式
    print("\n--- 使用享元模式 ---")
    start_time = time.time()
    
    char_factory = CharacterFactory()
    flyweight_objects = []
    contexts = []
    
    for i in range(num_objects):
        style_id = i % num_unique_styles
        style = CharacterStyle(f"Font{style_id}", 12 + style_id, f"color{style_id}")
        char = char_factory.get_character(style)
        context = CharacterContext(i * 10, i * 2, chr(65 + i % 26))
        flyweight_objects.append(char)
        contexts.append(context)
    
    flyweight_time = time.time() - start_time
    flyweight_memory = (char_factory.get_memory_usage() + 
                       sum(sys.getsizeof(ctx) for ctx in contexts))
    
    print(f"创建时间: {flyweight_time:.4f}秒")
    print(f"内存使用: {flyweight_memory} 字节")
    print(f"享元对象数: {char_factory.get_character_count()}")
    
    # 性能对比
    print("\n=== 性能对比结果 ===")
    time_improvement = (non_flyweight_time - flyweight_time) / non_flyweight_time * 100
    memory_improvement = (non_flyweight_memory - flyweight_memory) / non_flyweight_memory * 100
    
    print(f"时间改进: {time_improvement:.1f}%")
    print(f"内存改进: {memory_improvement:.1f}%")
    print(f"对象复用率: {(1 - char_factory.get_character_count() / num_objects) * 100:.1f}%")


def demonstrate_java_comparison():
    """
    演示与Java的对比
    """
    print("\n=== Python vs Java 享元模式对比 ===")
    
    print("\n=== Java实现特点 ===")
    print("""
    Java享元模式的实现:
    
    // Java享元接口
    public interface Flyweight {
        void operation(String extrinsicState);
    }
    
    // Java具体享元
    public class ConcreteFlyweight implements Flyweight {
        private String intrinsicState;
        
        public ConcreteFlyweight(String intrinsicState) {
            this.intrinsicState = intrinsicState;
        }
        
        @Override
        public void operation(String extrinsicState) {
            System.out.println("内部状态: " + intrinsicState + 
                             ", 外部状态: " + extrinsicState);
        }
    }
    
    // Java享元工厂
    public class FlyweightFactory {
        private Map<String, Flyweight> flyweights = new HashMap<>();
        
        public Flyweight getFlyweight(String key) {
            if (!flyweights.containsKey(key)) {
                flyweights.put(key, new ConcreteFlyweight(key));
            }
            return flyweights.get(key);
        }
    }
    """)
    
    print("\n=== Python实现优势 ===")
    print("""
    Python享元模式的优势:
    
    1. 弱引用支持:
       - weakref模块提供自动垃圾回收
       - 避免内存泄漏问题
    
    2. 装饰器模式:
       - @flyweight装饰器自动添加享元功能
       - 减少样板代码
    
    3. 动态类型:
       - 不需要严格的接口定义
       - 支持更灵活的内部状态
    
    4. 内置数据结构:
       - 字典和集合操作更简洁
       - 支持复杂的键类型
    
    5. 线程安全:
       - threading模块提供锁机制
       - 更容易实现线程安全的工厂
    """)
    
    print("\n=== 实际应用场景对比 ===")
    print("""
    应用场景对比:
    
    Java适合:
    - 大型游戏引擎中的粒子系统
    - 企业级应用的UI组件
    - 高性能图形渲染
    
    Python适合:
    - 文本编辑器的字符渲染
    - 数据可视化中的图形元素
    - Web应用的模板组件
    - 配置管理系统
    """)


def main():
    """
    主函数 - 演示所有享元模式实现
    """
    print("享元模式 (Flyweight Pattern) - Python实现演示")
    print("=" * 60)
    
    # 演示基本享元模式
    demonstrate_basic_flyweight()
    
    # 演示字符享元模式
    demonstrate_character_flyweight()
    
    # 演示图形享元模式
    demonstrate_shape_flyweight()
    
    # 演示线程安全享元工厂
    demonstrate_thread_safe_flyweight()
    
    # 演示享元装饰器
    demonstrate_flyweight_decorator()
    
    # 演示性能对比
    demonstrate_performance_comparison()
    
    # 演示Java对比
    demonstrate_java_comparison()
    
    print("\n=== 总结 ===")
    print("""
    享元模式的核心思想:
    1. 分离内部状态和外部状态
    2. 共享内部状态相同的对象
    3. 通过工厂管理享元对象的创建和复用
    
    Python实现的特点:
    1. 利用弱引用实现自动内存管理
    2. 使用装饰器简化享元实现
    3. 支持线程安全的享元工厂
    4. 灵活的键类型和内部状态管理
    
    适用场景:
    - 需要创建大量相似对象的场景
    - 对象的内部状态可以共享
    - 内存使用是关键考虑因素
    - 对象的创建成本较高
    """)


if __name__ == "__main__":
    main()